#include <termios.h>
#include <stdio.h>
#include <unistd.h>

#include <stdlib.h>
#include <sys/time.h>
#include <sys/types.h>

#include <stdio.h>
#include <termios.h>
#include <unistd.h>
#include <fcntl.h>
 
void init_kbhit(void)
{
  int ret;
  ret = system("stty -icanon min 1 time 0");   /* required for kbhit() */ 
}
 
/*bool kbhit(void)
{
  struct timeval tv = { 0, 0 };
  fd_set rfd;
   
  FD_ZERO(&rfd);
  FD_SET(0, &rfd);
  if(select(1, &rfd, NULL, NULL, &tv) > 0)
    return true;
  else
    return false;
}*/

/*
int kbhit(void)
{
  struct termios oldt, newt;
  int ch;
  int oldf;
 
  tcgetattr(STDIN_FILENO, &oldt);
  newt = oldt;
  newt.c_lflag &= ~(ICANON | ECHO);
  tcsetattr(STDIN_FILENO, TCSANOW, &newt);
  oldf = fcntl(STDIN_FILENO, F_GETFL, 0);
  fcntl(STDIN_FILENO, F_SETFL, oldf | O_NONBLOCK);
 
  ch = getchar();
 
  tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
  fcntl(STDIN_FILENO, F_SETFL, oldf);
 
  if(ch != EOF)
  {
    ungetc(ch, stdin);
    return 1;
  }
 
  return 0;
}*/

void clear_kbhit(void)
{
  getchar();
}

void kill_kbhit(void)
{
  int ret;
  ret = system("stty sane"); /* return stdin to a useable state */ 
}

//linux/unix solution for getch command
char getch(void)
{
				char buf = 0;
				struct termios old = {0};

				if (tcgetattr(0, &old) < 0)
								perror("tcsetattr()");

				old.c_lflag &= ~ICANON;
				old.c_lflag &= ~ECHO;
				old.c_cc[VMIN] = 1;
				old.c_cc[VTIME] = 0;

				if (tcsetattr(0, TCSANOW, &old) < 0)
								perror("tcsetattr ICANON");

				if (read(0, &buf, 1) < 0)
								perror ("read()");

				old.c_lflag |= ICANON;
				old.c_lflag |= ECHO;

				if (tcsetattr(0, TCSADRAIN, &old) < 0)
								perror ("tcsetattr ~ICANON");

				return (buf);
}

void changemode(int dir)
{
  static struct termios oldt, newt;
 
  if( dir == 1 )
  {
    tcgetattr( STDIN_FILENO, &oldt);
    newt = oldt;
    newt.c_lflag &= ~( ICANON | ECHO );
    tcsetattr( STDIN_FILENO, TCSANOW, &newt);
  }
  else
    tcsetattr( STDIN_FILENO, TCSANOW, &oldt);
}
 
int kbhit (void)
{
  struct timeval tv;
  fd_set rdfs;
 
  tv.tv_sec = 0;
  tv.tv_usec = 0;
 
  FD_ZERO(&rdfs);
  FD_SET (STDIN_FILENO, &rdfs);
 
  select(STDIN_FILENO+1, &rdfs, NULL, NULL, &tv);
  return FD_ISSET(STDIN_FILENO, &rdfs);
 
}
